//
//  ApiManager.swift
//  AESOLAR_IOS
//
//  Created by Mac on 2019/8/22.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import Moya

enum ThirdLoginType: String {
    case wechat = "1"
    case facebook = "2"
    case google = "3"
}

struct ApiManager {
    
    let path: String
    let parameters: [String: Any]
    let header: [String: String]?
    
    init(path: String, parameters: [String: Any] = [:], header: [String: String]? = nil) {
        self.path = path
        self.parameters = parameters
        self.header = header
    }
    
    // MARK: 登录
    static func getCode(_ email: String) -> ApiManager {
        return ApiManager(path: "photovoltaic/app-account/getvcode",
                          parameters: ["email": email])
    }
    
    static func login(email: String, vcode: String, subAccount: String?) -> ApiManager {
        var parameters: [String: Any] = ["email": email, "vcode": vcode, "platform": "1"]
        if let subAccount = subAccount {
            parameters["subAccount"] = ["id": subAccount]
        }
//        JPUSHService.registrationID()
        
        let registerId = JPUSHService.registrationID();
        if registerId.count > 0 {
            parameters["registrationId"] = registerId
        }
        
//        if let registrationId = JPUSHService.registrationID() {
//             parameters["registrationId"] = registrationId
//        }
        return ApiManager(path: "photovoltaic/app-account/login",
                          parameters: parameters)
    }
    
    static func wxAuth(_ code: String) -> ApiManager {
        return ApiManager.init(path: "photovoltaic/wxoauth/appauth",
                               parameters: ["appid": APPConfig.wxkey,
                                            "code": code])
    }
    
    static func thirdLogin(type: ThirdLoginType, appId: String?, openId: String, nickname: String?, userPic: String?) -> ApiManager {
        var parameters = ["type": type.rawValue,
                          "openId": openId]
        if let appId = appId {
            parameters["appId"] = appId
        }
        if let nickname = nickname {
            parameters["nickname"] = nickname
        }
        if let userPic = userPic {
            parameters["userPic"] = userPic
        }
        
        let registrationId = JPUSHService.registrationID()
        
        if registrationId.count > 0 {
             parameters["registrationId"] = registrationId
        }
        return ApiManager(path: "photovoltaic/app-third-party-account/login",
                          parameters: parameters)
    }
    
    static func getUserInfo(model: LoginModel) -> ApiManager {
        let header = [model.type: model.token]
        return ApiManager(path: "photovoltaic/app-account/detail",
                          parameters: ["id": model.userId],
                          header: header)
    }
    
    static func logOut() -> ApiManager {
        return ApiManager(path: "photovoltaic/app-account/loginout",
                          parameters: ["id": APPUser.shared.userId])
    }
    
    // MARK: 客诉
    static func getBarCode(_ uid: String) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-info/detailByUid",
                          parameters: ["uid": uid])
    }
    
    static func concatList(_ page: Int) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-complaint/list",
                          parameters: ["appAccountId": APPUser.shared.userId,
                                       "pageNum": "\(page)",
                            "pageSize": "10"])
    }
    
    static func deleteConcat(_ id: String) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-complaint/del",
                          parameters: ["appAccountId": APPUser.shared.userId,
                                       "id": id])
    }
    
    static func editConcat(id: String, model: AddConcatModel) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-complaint/update",
                          parameters: ["appAccountId": APPUser.shared.userId,
                                       "id": id,
                                       "contract": model.contract,
                                       "supplier": model.supplier,
                                       "content": model.content,
                                       "fileIds": model.fileIds])
    }
    
    static func getConfig() -> ApiManager {
        return ApiManager(path: "photovoltaic/sys-config/getConfig")
    }
    
    static func addConnact(model: AddConcatModel) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-complaint/add",
                          parameters: ["number": model.number,
                                       "contract": model.contract,
                                       "supplier": model.supplier,
                                       "content": model.content,
                                       "longitude": model.longitude,
                                       "latitude": model.latitude,
                                       "address": model.address,
                                       "fileIds": model.fileIds])
    }
    
    // MARK: 查验
    static func verify(_ uid: String, barcode: String, longitude: String, latitude: String, address: String) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-check/check",
                          parameters: ["uid": uid,
                                       "barcode": barcode,
                                       "longitude": longitude,
                                       "latitude": latitude,
                                       "address": address])
    }
    
    static func scanVerify(_ barcode: String, longitude: String, latitude: String, address: String) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-check/checkByCode",
                          parameters: ["barcode": barcode,
                                       "longitude": longitude,
                                       "latitude": latitude,
                                       "address": address])
    }
    
    static func scanCodePsrInfos(_ barcode: String) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-info/tempList", parameters: ["barcode": barcode])
    }
    
    static func fakeList(_ page: Int) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-report-false/list",
                          parameters: ["appAccountId": APPUser.shared.userId,
                                       "pageNum": "\(page)",
                                       "pageSize": "10"])
    }
    
    static func deleteFake(_ id: String) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-report-false/del",
                          parameters: ["appAccountId": APPUser.shared.userId,
                                       "id": id])
    }
    
    
    static func reportFake(psrCheckId: String,
                           productNumber: String,
                           purchaseChannel: String,
                           supplier: String,
                           purchaseNum: String,
                           content: String,
                           fileIds: [String],
                           contractNo: String,
                           buyTime: Double) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-report-false/add",
                          parameters: ["appAccountId": APPUser.shared.userId,
                                       "productNumber": productNumber,
                                       "psrCheckId": psrCheckId,
                                       "purchaseChannel": purchaseChannel,
                                       "supplier": supplier,
                                       "purchaseNum": purchaseNum,
                                       "content": content,
                                       "fileIds": fileIds,
                                       "contractNo": contractNo,
                                       "buyTime": buyTime])
    }
    
    static func editFake(id: String,
                         productNumber: String,
                         purchaseChannel: String,
                         supplier: String,
                         purchaseNum: String,
                         content: String,
                         fileIds: [String],
                         contractNo: String,
                         buyTime: Double) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-report-false/update",
                          parameters: ["appAccountId": APPUser.shared.userId,
                                       "id": id,
                                       "productNumber": productNumber,
                                       "purchaseChannel": purchaseChannel,
                                       "supplier": supplier,
                                       "purchaseNum": purchaseNum,
                                       "content": content,
                                       "fileIds": fileIds,
                                       "contractNo": contractNo,
                                       "buyTime": buyTime])
    }
    
    // MARK: 留言板
    static func messageList(_ page: Int) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-message-board/list",
                          parameters: ["appAccountId": APPUser.shared.userId,
                                       "pageNum": "\(page)",
                            "pageSize": "20"])
    }
    
    static func sendMessage(content: String = "", fileIds: [String] = []) -> ApiManager {
        return ApiManager(path: "photovoltaic/psr-message-board/add",
                          parameters: ["content": content,
                                       "fileIds": fileIds])
    }
    
    // MARK: 个人中心
    static func updateUserInfo(model: LoginModel? = nil, email: String?, name: String, phone: String, country: String, company: String, job: String, companyWebsite: String, remarks: String) -> ApiManager {
        var header: [String: String]?
        if let model = model {
            header = [model.type: model.token]
        }
        
        var parameters: [String: Any] = [:]
        parameters["id"] = model?.userId ?? APPUser.shared.userId
        parameters["name"] = name
        parameters["phone"] = phone
        parameters["country"] = country
        parameters["companyName"] = company
        parameters["position"] = job
        parameters["remarks"] = remarks
        parameters["companyWebsite"] = companyWebsite
        if let email = email {
            parameters["email"] = email
        }
        
        return ApiManager(path: "photovoltaic/app-account/update",
                          parameters: parameters,
                          header: header)
    }
    
    static func userInfo() -> ApiManager {
        return ApiManager(path: "photovoltaic/app-account/detail",
                          parameters: ["id": APPUser.shared.userId])
    }
    
    static func changeEmailSendCode(_ email: String) -> ApiManager {
        return ApiManager(path: "photovoltaic/app-account/changeEmailVcode",
                          parameters: ["email":  email])
    }
    
    static func changeEmail(email: String, vcode: String) -> ApiManager {
        return ApiManager(path: "photovoltaic/app-account/changeEmail",
                          parameters: ["email": email,
                                       "vcode": vcode])
    }
    
    static func shareSuccess() -> ApiManager {
        return ApiManager(path: "photovoltaic/app-account/share",
                          parameters: ["id": APPUser.shared.userId])
    }
    
}

extension ApiManager: TargetType {
    
    var task: Task {
        return .requestParameters(parameters: parameters,
                                  encoding: JSONEncoding.default)
    }
    
    var headers: [String : String]? {
        var header = ["Content-Type": "application/json"]
        
        header["CONSTANT_CURRENT_LANGUAGE"] = AppCache.shared.object(for: APPUserDefault.self).userSelectLanguage?.header ?? "en"
        
        if APPUser.shared.isLogin {
            header[APPUser.shared.userInfo.type] = APPUser.shared.token
        }
        
        if let customHeader = self.header {
            for key in customHeader.keys {
                header[key] = customHeader[key]
            }
        }
        
        return header
    }
}
